package core;

import java.io.ByteArrayInputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import log.ServerLogger;

import org.apache.mina.core.future.CloseFuture;
import org.apache.mina.core.future.IoFuture;
import org.apache.mina.core.future.IoFutureListener;
import org.apache.mina.core.service.IoHandler;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
import org.w3c.dom.Document;

import Ice.ForcedCloseConnectionException;
import connector.MsgConnectorPool;
import ui.ServerMainFrame;
import util.ServerCache;
import util.UserData;
import xml.ConnectMsg;
import xml.RequestBody;
import xml.ResponseBody;

/**
 * @see 处理服务器端消息
 * @author Herman.Xiong
 * @date 2012-6-26 下午01:12:34
 * @file ServerMessageHandler.java
 * @package com.minaqq.server
 * @project MINA_QQ
 * @version 1.0
 * @since jdk1.6,mina 2.0
 */
public class ServerMessageHandler extends  IoHandlerAdapter{

	public void exceptionCaught(IoSession session, Throwable cause) throws Exception {
		ServerLogger.Error("服务器-终端发生异常："+ cause.toString());
	}

	public void messageSent(IoSession session, Object message) throws Exception {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		String datetime = sdf.format(new Date());
		ServerLogger.DEBUG("服务器发送消息messageSent----------： "+message.toString());
	}

	public void sessionClosed(IoSession session) throws Exception {
		//ServerDisplay.getInstance().updataOnlineNum();
		//ServerCache.getInstance().setOnlineNum(session.)

		ServerLogger.DEBUG("关闭当前session: "+session.getId()+session.getRemoteAddress());
		CloseFuture closeFuture = session.close(true);


		ServerCache servercache = ServerCache.getInstance();
		//登陆时把loginMessage的loginID作为根据放入到cache中，不能用owerQQ可能重复登陆
		String useridip = servercache.getOnLineUserMap().get(session.getId());

		servercache.removeUserConnect(useridip);

		servercache.removeUserFromeOnlineList(session.getId());

		servercache.removeIdMap(session.getId());
		/*
		if(servercache.getIdMap().containsValue(userid))
		{
			//servercache.removeUserFromeOnlineList(servercache.getIdMap().get(session.getId()));
		}else
		{
			servercache.removeUserFromeOnlineList(userid);
		}
		 */
		ServerLogger.INFO(session.getRemoteAddress()+"关闭了连接"+"\n");
		ServerMainFrame.getInstance().updataOnlineNum();
		ServerMainFrame.getInstance().updataOnlineUser();

		closeFuture.addListener(new IoFutureListener<IoFuture>() {
			public void operationComplete(IoFuture future) {
				if (future instanceof CloseFuture) {
					((CloseFuture) future).setClosed();
					ServerLogger.DEBUG("客户端关闭"+ future.getSession().getId());
				}
			}
		});

	}

	public void sessionCreated(IoSession session) throws Exception {
		super.sessionCreated(session);
		ServerLogger.INFO("创建一个新连接："+ session.getRemoteAddress()+"  id:  "+session.getId());
		// 向所有客户端发送数据
		//String senstr = new ConnectMsg().createDocument(session.getId());
		//session.write(senstr);
	}

	public void sessionIdle(IoSession session, IdleStatus status) throws Exception {

		ServerLogger.INFO(session.getId()+"当前连接处于空闲状态："+ session.getRemoteAddress()+ status);
		session.close(true);
	}

	public void sessionOpened(IoSession session) throws Exception {
		System.out.println("打开一个session id："+ session.getId()+"  空闲连接个数IdleCount：  "+ session.getBothIdleCount());
		//ServerDisplay.getInstance().updataOnlineNum();

	}
	public void messageReceived(IoSession session, Object message) throws Exception {
		String msg = message.toString();
		System.out.println("收到客户端数据messageReceived----------："+ msg.toString());
		RequestBody requestBody = (RequestBody) message;
		if(requestBody.getType().equals("id_request"))
		{
			String sessionId = Long.toString(session.getId());
			String userId = requestBody.get("idip");
			
			String userName = requestBody.get("user");
			String userip = session.getRemoteAddress().toString();
			boolean isonline;
			if(requestBody.get("isonline").equals("1"))//已登录用户
			{
				isonline = true;
			}else
			{
				isonline = false;
				userName = "";
			}

			ServerCache servercache = ServerCache.getInstance();
			ResponseBody body = new ResponseBody();
			body.setType("id_response");
			body.setSender("0");
			body.setReciever(sessionId);
			if(userId.equals("0"))//首次连接
			{
				body.put("id",sessionId);
				body.put("idip",sessionId+":"+session.getRemoteAddress());
				servercache.addIdMap(session.getId(), "未登录"+userip);
				servercache.addUserConnect(sessionId+":"+session.getRemoteAddress(),session);//添加到连接列表
				//登陆时把loginMessage的loginID作为根据放入到cache中，不能用owerQQ可能重复登陆
				//UserData user = new UserData(sessionId, userName, isonline, userip);
				servercache.addUserToOnLineList(session.getId(), sessionId+":"+session.getRemoteAddress());
			}else //断线连接
			{
				String uId = requestBody.get("userid");
				body.put("id",uId);
				body.put("idip",uId+":"+session.getRemoteAddress());
				servercache.addIdMap(session.getId(), userName+userip);
				servercache.addUserConnect(uId+":"+session.getRemoteAddress(),session);//添加到连接列表
				//登陆时把loginMessage的loginID作为根据放入到cache中，不能用owerQQ可能重复登陆
				//UserData user = new UserData(userId, userName, isonline, userip);
				servercache.addUserToOnLineList(session.getId(), uId+":"+session.getRemoteAddress());
			}
			String version = Global.getInstance().getUpdateVersion_android();
			body.put("android_lastversion",version);
			//返回id
			ServerMainFrame.getInstance().updataOnlineNum();
			ServerMainFrame.getInstance().updataOnlineUser();
			session.write(body);

		}else if(requestBody.getType().equals("heartbeat_request"))
		{
			ServerCache servercache = ServerCache.getInstance();
			String userName = requestBody.get("user");
			String userip = session.getRemoteAddress().toString();
			if(requestBody.get("isonline").equals("1"))//已登录用户
			{
				servercache.addIdMap(session.getId(), userName+userip);
			}else
			{
				servercache.addIdMap(session.getId(), "未登录"+userip);
				//userName = "";
			}

			ServerMainFrame.getInstance().updataOnlineUser();
			
			ResponseBody body = new ResponseBody();
			body.setType("heartbeat_response");
			body.setSender("0");
			body.setReciever(servercache.getOnLineUserMap().get(session.getId()));
			session.write(body);

		}else if(requestBody.getType().equals("login_request"))
		{
			ServerCache servercache = ServerCache.getInstance();
			/*
			String loginName = requestBody.get("account");
			if(servercache.getOnLineUserMap().containsValue(loginName))
			{
				ResponseBody body = new ResponseBody();
				body.setType("login_response");
				body.setSender("0");
				body.setReciever(Long.toString(session.getId()));
				body.put("login_code", "000002");
				session.write(body);
			}else
			{
				String front_code = "80000002";
				MsgConnectorPool.getInstants().addHccConnector(front_code+message.toString());
			}
			 */
			String front_code = "80000002";
			MsgConnectorPool.getInstants().addHccConnector(front_code+message.toString());

			/*
			Random rand =new Random();
			int i = rand.nextInt(100);
			ResponseBody body = new ResponseBody();
			body.setType("login_response");
			body.setSender("0");
			body.setReciever(Long.toString(session.getId()));
			body.put("login_code", "success");
			body.put("ye", "余额:"+i+"元");
			i = rand.nextInt(1000);
			body.put("bjsz", "表计示值:"+i+"kw");
			body.put("fmzt", "阀门状态:开");
			i = rand.nextInt(100);
			body.put("zje", "总金额:"+i+"元");
			i = rand.nextInt(20);
			body.put("jswd", "进水温度:"+i+"℃");
			i = rand.nextInt(35);
			body.put("hswd", "回水温度:"+i+"℃");
			i = rand.nextInt(10);
			body.put("ls", "流速:"+i+"m³");
			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
			body.put("refreshtime",df.format(new Date()));
			session.write(body);
			 */

		}else if(requestBody.getType().equals("loginsync_request"))
		{
			ServerCache servercache = ServerCache.getInstance();
			String userName = requestBody.get("username");
			String userip = session.getRemoteAddress().toString();
			servercache.addIdMap(session.getId(), userName+userip);
			ServerMainFrame.getInstance().updataOnlineUser();
		}
		else if(requestBody.getType().equals("roomview_request"))
		{
			/*
			Random rand =new Random();
			int i = rand.nextInt(100);
			ResponseBody body = new ResponseBody();
			body.setType("energydata_response");
			body.setSender("0");
			body.setReciever(Long.toString(session.getId()));
			body.put("ye", "余额:"+i+"元");
			i = rand.nextInt(1000);
			body.put("bjsz", "表计示值:"+i+"kw");
			body.put("fmzt", "阀门状态:开");
			i = rand.nextInt(100);
			body.put("zje", "总金额:"+i+"元");
			i = rand.nextInt(20);
			body.put("jswd", "进水温度:"+i+"℃");
			i = rand.nextInt(35);
			body.put("hswd", "回水温度:"+i+"℃");
			i = rand.nextInt(10);
			body.put("ls", "流速:"+i+"m³");
			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
			body.put("refreshtime",df.format(new Date()));
			session.write(body);
			 */
			String front_code = "80000003";
			MsgConnectorPool.getInstants().addHccConnector(front_code+message.toString());
		}else if(requestBody.getType().equals("register_request"))
		{
			/*
			ResponseBody body = new ResponseBody();
			body.setType("register_response");
			body.setSender("0");
			body.setReciever(Long.toString(session.getId()));
			body.put("register_code", "000001");
			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
			body.put("register_time",df.format(new Date()));
			session.write(body);
			 */
			String front_code = "80000001";
			MsgConnectorPool.getInstants().addHccConnector(front_code+message.toString());

		}
		else if(requestBody.getType().equals("nlbdata_request"))
		{

			//String front_code = "80000005";
			//MsgConnectorPool.getInstants().addHccConnector(front_code+message.toString());
			String startTime = requestBody.get("starttime");
			String endTime = requestBody.get("endtime");
			
			String format = "yyyy-MM-dd HH";
			Date start = new SimpleDateFormat(format).parse(startTime);
			Date end = new SimpleDateFormat(format).parse(endTime);
			
			ResponseBody body = new ResponseBody();
			body.setType("nlbdata_response");
			body.setSender("0");
			body.setReciever(Long.toString(session.getId()));
			body.put("starttime", startTime);
			body.put("endtime", endTime);
			for(int i=0;i<7;i++)
			{
				for(int j=0;j<24;j++)
				{
					Random random = new Random();//指定种子数100
					String time = String.format("a%d-%d-%d-%d", start.getYear()+1900,start.getMonth(),i,j);
					float randomNum = random.nextInt(40);
					body.put(time, String.valueOf(randomNum));
				}
				
			}
			session.write(body);

		}else if(requestBody.getType().equals("forcecontrol_request"))
		{

			String front_code = "80000006";
			MsgConnectorPool.getInstants().addHccConnector(front_code+message.toString());

			//String front_code = "80000002";
			//MsgConnectorPool.getInstants().addHccConnector(front_code+message.toString());

		}else if(requestBody.getType().equals("rechargepara_request"))
		{

			//String front_code = "80000013";
			//MsgConnectorPool.getInstants().addHccConnector(front_code+message.toString());

			ResponseBody body = new ResponseBody();
			body.setType("rechargepara_response");
			body.setSender("0");
			body.setReciever(Long.toString(session.getId()));
			session.write(body);

		}else if(requestBody.getType().equals("recharge_request"))
		{

			String front_code = "80000009";
			MsgConnectorPool.getInstants().addHccConnector(front_code+message.toString());
/*
			ResponseBody body = new ResponseBody();
			body.setType("recharge_response");
			body.setSender("0");
			body.setReciever(Long.toString(session.getId()));
			body.put("account", "000001");
			body.put("room", "000001");
			body.put("rechargestate", "000000");
			session.write(body);
			*/
		}
		else if(requestBody.getType().equals("selectcharge_request"))
		{

			String front_code = "80000022";
			MsgConnectorPool.getInstants().addHccConnector(front_code+message.toString());
/*
			ResponseBody body = new ResponseBody();
			body.setType("recharge_response");
			body.setSender("0");
			body.setReciever(Long.toString(session.getId()));
			body.put("account", "000001");
			body.put("room", "000001");
			body.put("rechargestate", "000000");
			session.write(body);
			*/
		}
		else if(requestBody.getType().equals("rechargesync_request"))
		{

			//String front_code = "80000013";
			//MsgConnectorPool.getInstants().addHccConnector(front_code+message.toString());

			ResponseBody body = new ResponseBody();
			body.setType("rechargesync_response");
			body.setSender("0");
			body.setReciever(Long.toString(session.getId()));
			body.put("account", "000001");
			body.put("room", "000001");
			body.put("bill", "000001");
			session.write(body);
		}else if(requestBody.getType().equals("changepwd_request"))
		{

			//String front_code = "80000013";
			//MsgConnectorPool.getInstants().addHccConnector(front_code+message.toString());

			String front_code = "80000011";
			MsgConnectorPool.getInstants().addHccConnector(front_code+message.toString());
		}else if(requestBody.getType().equals("reportrepair_request"))
		{

			//String front_code = "80000013";
			//MsgConnectorPool.getInstants().addHccConnector(front_code+message.toString());

			String front_code = "80000008";
			MsgConnectorPool.getInstants().addHccConnector(front_code+message.toString());
		}
		else if(requestBody.getType().equals("timingcontrol_request"))
		{

			//String front_code = "80000013";
			//MsgConnectorPool.getInstants().addHccConnector(front_code+message.toString());

			String front_code = "80000007";
			MsgConnectorPool.getInstants().addHccConnector(front_code+message.toString());
		}
		/*
		//请求协议
		mp.setMsgMethod(3000);
		mp.setMsgPack("我是服务器发的消息");
		mp.setMsgLength(mp.getMsgPack().getBytes().length);
        session.write(mp);
		 */
		/*String content = mp.toString();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        String datetime = sdf.format(new Date());
        System.out.println(datetime+"服务器接收到数据的内容为messageReceived----------: " + content);*/
		// 拿到所有的客户端Session
		/*Collection<IoSession> sessions = session.getService().getManagedSessions().values();
        // 向所有客户端发送数据
        for (IoSession sess : sessions) {
            sess.write(datetime + "\t" + content);
        }*/

	}

}
